package UDPdemo;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * Created with Intellij IDEA.
 * Description:
 * User: 33013
 * Date: 2023-10-11
 * Time: 20:08
 */
public class UDPechoServer{
    private DatagramSocket socket = null;

    public UDPechoServer(int port) throws SocketException {
        socket = new DatagramSocket(port);
    }

    public void start() throws IOException {
        while (true){
            DatagramPacket req = new DatagramPacket(new byte[4064], 4064);
            socket.receive(req);
            String strreq = new String(req.getData(), 0, req.getLength());
            String strresp = press(strreq);
            DatagramPacket resp = new DatagramPacket(strresp.getBytes(), strresp.getBytes().length, req.getSocketAddress());
            socket.send(resp);
            System.out.printf("[%s: %d] req: %s, res: %s\n", req.getAddress().toString(), req.getPort(), strreq, strresp);
        }
    }

    public String press(String req) {
        return req;
    }

    public static void main(String[] args) throws IOException {
        UDPechoServer server = new UDPechoServer(9090);
        server.start();
    }
}
